<template>
  <div class="mavon-toolbars">
    <div class="title">
      <span @click="((publishPopUpShow = false) + (attPopUpShow = true))">完善信息</span>
      <span @click="((publishPopUpShow = true) + (attPopUpShow = false))">发表文章</span> 
    </div>
    <div id="editor-create">
      <mavon-editor  ref="my-mavon-editor"
        v-model="markdownValue"
        :ishljs="true"
        :toolbars="toolbars()"
        @imgAdd="$imgAdd" @imgDel="$imgDel"
      />
    </div>

    <!-- 发布部分 start -->
    <div class="window-pop-up" v-show="publishPopUpShow">
      <div class="item-box">
        <div class="item-att">Title</div>
        <div class="item-content"> <input type="text" name="headline" ref="headline"> </div>
      </div>
      <div class="item-box">
        <div class="item-att">Functionality</div>
        <div class="item-content"> 
          <select name="" id="" v-model="functionalityId" class="functionality-box">
            <option class="functionality" :value="functionality.id" v-for="functionality of functionalities" :key="functionality.id">
              {{functionality.name}}
            </option>
          </select>
        </div>
      </div>
      <div class="item-box">
        <div class="item-att">Cover_url</div>
        <div class="item-content cover_url-box">
          <input @change="uploadArticleCover" class="file" type="file" name="cover_url">
          <div class="cover_url" ref="cover_url">选择图片</div>
        </div>
      </div>
      <div class="item-box publsh-box">
        <span class="publsh-btn" @click="submit">
          {{operateType}}
        </span>
      </div>
    </div>
    <!-- 发布部分 end -->

    <div class="window-pop-up" v-show="attPopUpShow">
      <div class="item-box">
        <div class="item-att">Outline</div>
        <div class="item-content">
          <textarea id=""  name="outline" ref="outline"></textarea>
        </div>
      </div>
      <div class="item-box">
        <div class="item-att">Tags</div>
        <div class="item-content"> 
          <div class="tag-tree-box" v-if="tagTree">
            <div class="tagclass-box flex" @click="changeTagclass">
              <div class="tagclass" :data-index="index" v-for="(tagclass, index) of tagTree" :key="tagclass.id">{{tagclass.name}}</div>
            </div>
            <div class="check-tags flex" @click="checkTag">
              <div class="tag" :data-index="index" v-for="(tag, index) of checkTagclass" :key="tag.id">{{tag.name}}</div>
            </div>

            <div class="checked-tag-box" @click="cancelCheckTag">
              <div class="tag-att-title">已选</div>
              <div class="checked-tag" :data-index="index" v-for="(tag, index) of checkedTags" :key="tag.id">
                {{tag.name}}
              </div>
            </div>

          </div>
        </div>
      </div>
      <div class="item-box success-box publsh-box">
        <span class="success-btn publsh-btn" @click="attPopUpShow = false">
          OK
        </span>
      </div>
    </div>

  </div>
</template>

<script>
import { GET_TAG_TREE, GET_FUNCTIONALITIES } from '__STORE__/operation-type'
import { uploadArticleCover, uploadArticleImage } from '__SERVICE__/files.js'
import { publishArticle } from '__SERVICE__/article.js'
import MavonEditorMxin from '__COMPONENTS__/mavon_editor/base-mixin.js'

const { VUE_APP_PROXY_PATH: PROXY_PATH } = process.env
const $SERVER_URL = '/' + PROXY_PATH
export default {
  mixins: [MavonEditorMxin],
  name: 'MyMavonEditor',
  props: ['operateType'],
  computed: {
    tags() {
      return this.$store.getters.tags
    }
  },
  data: () => ({
    markdownValue: '',
    tagTree: null,
    checkTagclass: null,
    functionalities: [],
    checkedTags: [],
    attPopUpShow: false,
    publishPopUpShow: false,
    functionalityId: undefined
  }),
  created() {
    this.getTags()
    this.getFunctionalities()
  },
  mounted() {

  },
  methods: {
    //留下来的初始化
    async init(article) {
      this.markdownValue = article.content // 内容
      this.functionalityId = article.functionality_id // 功能
      this.$refs['headline'].value = article.headline
      this.$refs['outline'].value = article.outline
      this.$refs['cover_url'].style.backgroundImage =  `url(${article.cover_url})`
      this.$refs['cover_url'].innerHTML = ''
      if(!this.tags.length) {
        await this.getTags()
      }
      this.checkedTags = JSON.parse(article.tag_ids).map((id)=>{
        const tag = this.tags.find((tag)=>{
          return id == tag.id
        })
        return Object.freeze(tag)
      })
    },
    async getTags() {
      try {
        const dataRsource = this.$store.state.globalConfig
        //如果没有等待 获取数据
        if(!dataRsource.tagTree) await this.$store.dispatch(GET_TAG_TREE)
        //成功获取数据
        const tagclasses = dataRsource.tagTree
        this.tagTree = Object.freeze(tagclasses)
        this.checkTagclass = tagclasses[0] && tagclasses[0].tag_models
      }catch(e) {
        console.log(e.message)
      }
    },
    async getFunctionalities() {
      try {
        const dataRsource = this.$store.state.globalConfig
        //如果没有等待 获取数据
        if(!dataRsource.functionalities ) await this.$store.dispatch(GET_FUNCTIONALITIES)
        //成功获取数据
        const functionalities = dataRsource.functionalities 
        this.functionalities = Object.freeze(functionalities)
      }catch(e) {
        console.log(e.message)
      }
    },
    //切换tagclass的逻辑 start
    changeTagclass(e) {
      const target = e.target
      if(target.className === 'tagclass') {
        const index = target.dataset.index
        this.checkTagclass = this.tagTree[index].tag_models
      }
    },
    //切换tagclass的逻辑 end
    //选择tag的逻辑 start
    checkTag(e) {
      if(this.checkedTags.length >= 3) {
        this.$Notice.state({title: '操作失败', desc: '最多只能三个', duration: 3000})
        return false
      }
      const target = e.target
      if(target.className === 'tag') {
        const index = target.dataset.index
        const newTag = this.checkTagclass[index]
        const isRepeat = !!this.checkedTags.find((checkedTag)=>{ //是否重复
          return checkedTag.id == newTag.id
        })
        if(!isRepeat){//不重复
           this.checkedTags.push(Object.freeze(newTag))
        }else {//重复通知
          this.$Notice.state({
            title: '操作错误', desc: '重复选择，请点击下方已选标签取消', duration: 3000
          })
        }
      }
    },
    //选择tag的逻辑 end
    // 取消选择tag的逻辑 start
    cancelCheckTag(e) {
      const target = e.target
      if(target.className === 'checked-tag') {
        const index = target.dataset.index
        this.checkedTags.splice(index, 1)
      }
    },
    // 取消选择tag的逻辑 end
    //真正提交发布文章的地方 start
    async submit() {
      const { user_id, access_token } = this.$store.state.user.deadUserInfo
      if(!user_id || !access_token) {
        this.$Notice.state({title: '权限不允许', desc: '请先登入', duration: 3000})
        this.publishPopUpShow = false
        return
      }
      const content = this.markdownValue //内容
      const functionality_id = this.functionalityId
      const headline = this.$refs['headline'].value
      const outline = this.$refs['outline'].value
      const cover_url = this.$refs['cover_url'].style.backgroundImage && this.$refs['cover_url'].style.backgroundImage.match(/url\("(\S*)"\)/)[1]
      const tag_ids = this.checkedTags.map((tag)=>{
        return tag.id
      })
      //交由上层处理
      this.$emit(this.operateType, {
        content, headline, outline, cover_url, tag_ids, functionality_id,
        user_id, access_token
      })
      //关闭弹窗
      this.publishPopUpShow = false
    },
    //真正提交发布文章的地方 end
    async uploadArticleCover(e, data) {
      const target = e.target
      const formdata = this.getFileFormData(target)
      try {
        const result = await uploadArticleCover(formdata)
        const {data: {upload_url}} = result
        this.$refs['cover_url'].style.backgroundImage = `url(${$SERVER_URL + upload_url})`
        this.$refs['cover_url'].innerHTML = ''
      }catch(e) {
        console.log(e)
      }
    },
    // 获取文件的 fromdata形式 start
    getFileFormData(target) {
      const file = target.files[0]
      const fileName = file.name
      const fileSuffixIndex = fileName.lastIndexOf('.')
      const filePreffix = fileName.slice(0, fileSuffixIndex)
      const fileSuffix = fileName.slice(fileSuffixIndex+1)
      if('jpg png jpeg gif'.indexOf(fileSuffix) === -1) { // 文件格式无法匹配
        this.$Notice.error({title: '格式有误', desc: '只允许：jpg / png / jpeg / gif / ico', duration: 3000})
        return null
      }
      const formdata = new FormData()
      formdata.append(filePreffix, file)
      return formdata
    },
    // 获取文件的 fromdata形式 end
    async $imgAdd(pos, $file) {
      var formdata = new FormData();
      formdata.append("image", $file);
      const result = await uploadArticleImage(formdata)
      const {data: {upload_url}} = result
      this.$refs['my-mavon-editor'].$img2Url(pos, $SERVER_URL + upload_url);
    },
    $imgDel(file) {//删除图片

    }
  }
}
</script>

<style lang="less">
  @import url('__COMPONENTS__/mavon_editor/base_style.less');
  @import url('__COMPONENTS__/mavon_editor/toolbars_style.less');
</style>